package util;

/**
 * reference: http://lovecooldog.javaeye.com/blog/555514
 */
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public final class HibernateUtil {

    private static SessionFactory sessionFactory;
    private static ThreadLocal threadSession = new ThreadLocal();

    private HibernateUtil() {
    }

    static {
        Configuration cfg = new Configuration();
        cfg.configure();
        sessionFactory = cfg.buildSessionFactory();
    }

    public static Session getThreadLocalSession() {
        Session s = (Session) threadSession.get();
        if (s == null) {
            s = getSession();
            threadSession.set(s);
        }
        return s;
    }

    public static void closeSession() {
        Session s = (Session) threadSession.get();
        if (s != null) {
            s.close();
            threadSession.set(null);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    private static Session getSession() {
        return sessionFactory.openSession();
    }

    public static boolean insert(Object newObject) {
        Session session = null;
        Transaction tx = null;
        try {
            session = getThreadLocalSession();
            tx = session.beginTransaction();
            session.save(newObject);
            tx.commit();
            return true;
        } catch (Exception e) {
            tx.rollback();
            return false;
        } finally {
            if (session != null) {
                closeSession();
            }
        }
    }

    public static boolean delete(Object target) {
        Session session = null;
        Transaction tx = null;
        try {
            session = getThreadLocalSession();
            tx = session.beginTransaction();
            session.delete(target);
            tx.commit();
            return true;
        } catch (Exception e) {
            tx.rollback();
            return false;
        } finally {
            if (session != null) {
                closeSession();
            }
        }
    }

    public static boolean update(Object target) {
        Session session = null;
        Transaction tx = null;
        try {
            session = getThreadLocalSession();
            tx = session.beginTransaction();
            session.update(target);
            tx.commit();
            return true;
        } catch (Exception e) {
            tx.rollback();
            return false;
        } finally {
            if (session != null) {
                closeSession();
            }
        }
    }
}
